import { ISize } from "./interface/commTypes";
import { mat4, vec3 } from 'gl-matrix';

export default class Camera {
    position: [number, number, number];
    targetPosition: [number, number, number];
    rotation: [number, number, number];
    fov: number;
    aspectRatio: number;
    near: number;
    far: number;

    constructor(fov: number = 60, aspectRatio: number = 1, near: number = 1, far: number = 3000) {
        this.position = [0, 0, 600]; // 默认位置
        this.targetPosition = [0, 0, 0]; // 默认目标位置
        this.rotation = [0, 0, 0]; // 默认旋转角度（弧度）
        this.fov = fov; // 视场角（度）
        this.aspectRatio = aspectRatio; // 宽高比
        this.near = near; // 近裁剪面
        this.far = far; // 远裁剪面
    }
    
    resize(size: ISize) {
        this.aspectRatio = size.width / size.height;
    }

    viewMatrix: mat4 | null = null;
    // 获取视图矩阵
    getViewMatrix(): mat4  {
        if(!this.viewMatrix){

            const viewMatrix = mat4.create();
            mat4.lookAt(viewMatrix, this.position, this.targetPosition, [0, 1, 0]);
    
            // viewMatrix 按照行列输出
            // let str = "";
            // for (let i = 0; i < 4; i++) {
            //     // console.log(viewMatrix[i], viewMatrix[i + 4], viewMatrix[i + 8], viewMatrix[i + 12]);
            //     str +=`${viewMatrix[i]} ${viewMatrix[i + 4]} ${viewMatrix[i + 8]} ${viewMatrix[i + 12]}\n`
            // }
            // console.log('viewMatrix:\n', str)
    
            return viewMatrix;
        }

        return this.viewMatrix;

    }

    // 获取投影矩阵
    getProjectionMatrix(): mat4 {
        return mat4.perspective(mat4.create(), this.fov * Math.PI / 180, this.aspectRatio, this.near, this.far);
    }

    // 设置位置
    setPosition(x: number, y: number, z: number): void {
        this.position = [x, y, z];
    }

    // 设置旋转
    setRotation(rx: number, ry: number, rz: number): void {
        this.rotation = [rx, ry, rz];
    }

    // 设置目标位置并自动计算旋转
    setTargetPosition(x: number, y: number, z: number): void {
        this.targetPosition = [x, y, z];
    }
    
    // 设置视场角
    setFov(fov: number): void {
        this.fov = fov;
    }

    // 设置宽高比
    setAspectRatio(aspectRatio: number): void {
        this.aspectRatio = aspectRatio;
    }

    // 设置近裁剪面
    setNear(near: number): void {
        this.near = near;
    }

    // 设置远裁剪面
    setFar(far: number): void {
        this.far = far;
    }
}
